package com.atguigu.gmall.order.listener;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.common.config.mq.MqService;
import com.atguigu.gmall.mq.ware.WareStockResultMsg;
import com.atguigu.gmall.order.biz.OrderBizService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Slf4j
@Service
public class OrderStockListener {

    @Autowired
    OrderBizService orderBizService;
    @Autowired
    MqService mqService;

    //监听扣库存结果的 队列 queue.ware.order
    @RabbitListener(bindings = {//在此用注解的方式声明监听的队列，如果没有就自动创建一个 消息队列
            @QueueBinding(
                value = @Queue(value = "queue.ware.order",durable = "true",exclusive = "false",autoDelete = "false"),
                exchange = @Exchange(value = "exchange.direct.ware.order",durable = "true",autoDelete = "false"),
                key = "ware.order"
            )
    })
    public void listen(Message message, Channel channel) throws IOException {
        String content = new String(message.getBody());//消息体{"orderId":"","status":""}
        long deliveryTag = message.getMessageProperties().getDeliveryTag();

        try {
            //string 转为 bean对象
            WareStockResultMsg resultMsg = JSON.parseObject(content, WareStockResultMsg.class);
            log.info("监听到的库存扣减结果：{}",content);

            //修改订单状态
            orderBizService.updateOrderStockStatus(resultMsg);

            //收到消息，回复ok
            channel.basicAck(deliveryTag, false);
        } catch (Exception e){
            //没有收到消息，重试
            mqService.retry(channel, deliveryTag, content, 5);
        }

    }
}
